<template>
  <!-- 增加事项 -->
    <el-form :model="data"  ref="form" label-width="150px" size="small" label-position="right">
      <!--  -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="事项类型" prop="name">
            <el-input  v-model="data.name" placeholder="请输入" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联设备设施" prop="linkedDevice"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
            <el-select v-model="data.linkedDevice" :placeholder="'请选择关联设备设施'" :disabled="!isEdit" >
              <el-option v-for="item in linkedDevice" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <div v-if="data.linkedDevice==0">
          <el-col :span="12">
            <el-form-item label="选择子系统" prop="system" :disabled="!isEdit"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.system" :placeholder="'请选择子系统'">
                <el-option v-for="item in system" :key="item.primaryKey" :label="item.systemName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="选择设备" prop="device"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.device" :placeholder="'请选择设备'" :disabled="!isEdit">
                <el-option v-for="item in device" :key="item.primaryKey" :label="item.deviceName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
        </div>
          <el-col :span="12" >
            <el-form-item label="选择设施" prop="facility"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.facility" :placeholder="'请选择设施'" :disabled="!isEdit">
                <el-option v-for="item in facility" :key="item.primaryKey" :label="item.stationName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择功能分区" prop="spacePartition"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.spacePartition" :placeholder="'请选择功能分区'" @change="spacePartitionChange" :disabled="!isEdit">
                <el-option v-for="item in spacePartition" :key="item.primaryKey" :label="item.partitionName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择楼层" prop="floor"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.floor" :placeholder="'请选择楼层'" :disabled="!isEdit">
                <el-option v-for="item in floor" :key="item.primaryKey" :label="item.floorName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否资本性支出" prop="ifCapitalPayment"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.ifCapitalPayment" :placeholder="'请选择是否资本性支出'" :disabled="!isEdit">
                <el-option v-for="item in ifCapitalPayment" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="data.ifCapitalPayment">
            <el-form-item label="关联资本性支出类型" label-width="180px" prop="capitalPaymentType"  :rules="{required: true, message: '请选择', trigger: 'blur'}">
              <el-select v-model="data.capitalPaymentType" :placeholder="'请选择关联资本性支出类型'" :disabled="!isEdit">
                <el-option v-for="item in capitalPaymentType" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总成本">
              <el-input type="number" disabled v-model="total" :step="10" placeholder="自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="付款计划">
              <span class="addSpan"  @click="addPlan">增加</span>
            </el-form-item>
          </el-col>
          <div v-for="(item, index) in paymentItemListCloudDto" :key="index">
            <el-col :span="11">
              <el-form-item label="付款时间">
                <el-date-picker v-model="item.paymentDate" type="date" placeholder="请选择付款时间" :disabled="!isEdit"> </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="付款金额">
                <el-input type="number" :disabled="!isEdit" v-model="item.paymentAmount" :step="10" placeholder="请输入付款金额" @focus="focus(index)"  @blur="changePrice(index)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <span class="text-del" @click="remove(index)">删除</span>
            </el-col>
          </div>
        </el-row>
         <div v-if="showFile">
          <el-col :span="24" style="min-height:50px;">
            <el-form-item label="附件" style="margin-bottom:0!important;">
              <el-upload class="upload-demo"  :file-list="fileList" action="no" :on-remove="handleRemove" :http-request="event => beforeupload(event.file)">
                <el-button type="primary" plain class="addSpan" style="margin-right: 10px" size="mini">上传附件</el-button>
              </el-upload>
              <el-button type="text" v-for="(file, i) in businessAttachmentMapListCloudDto" :key="i" @click="DownFile(file)">{{ file.fileTitle }} </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="height:50px;">
            <el-form-item label="提示："> {{ errorMessage.resultMessage }} </el-form-item>
          </el-col>
          <el-col :span="24" style="height:50px;">
            <el-form-item label="说明：">
              <el-input size="mini" type="textarea" autosize v-model="data.configDesc"></el-input>
            </el-form-item>
          </el-col>
        </div>        
      
      <el-col v-if="isEdit">
          <el-form-item>
            <div class="t-right padding-top-15" >
              <el-button  type="primary" size="small" @click="save('form')" plain>确定</el-button>
            </div>
          </el-form-item>
      </el-col>
    </el-form>
</template>

<script>
import { uploadPhoto } from '@/api';
import Api from '../../../../api/incomeAndExpenditurePlan';
export default {
  props: {
    equipmentData: {
      type: Object,
      default:()=>{},
    },
    assetCode:{
      type: String,
      default:'',
    },
    isEdit:{
      type: Boolean,
      default:false,
    },
  },
  watch:{
    'data.system':{
      immediate:true,
      deep:true,
      handler(val){
        if(val){
          this.getDictionary(val);
        }
      }
    }
  },
  data() {
    return {
      total:0,
      data: {},
      businessAttachmentMapListCloudDto:[],
      paymentItemListCloudDto:[],
      showFile:false,
      fileList:[],
      paymentMethod: [], //付款方式
      linkedDevice: [
        {
          name: '设备',
          id: '0',
        },
        {
          name: '设施',
          id: '1',
        },
      ], //关联设备设施
      system: [], //子系统
      device: [], //设备
      facility: [], //设施
      spacePartition: [], //功能分区
      floor: [], //楼层
      ifCapitalPayment: [
        {
          id: 1,
          name: '是',
        },
        {
          id: 0,
          name: '否',
        },
      ], //是否资本性支出
      capitalPaymentType: [
        {
          name: '项目更新改造、店面提升',
          id: '0',
        },
        {
          name: '设备更新、大中修',
          id: '1',
        },
        {
          name: '屋面防水工程',
          id: '2',
        },
        {
          name: '大额设备设施损坏',
          id: '3',
        },
      ], //关联资本性支出类型
      
      getDictionaryDetail:{},
    };
  },
  created(){
    this.getDictionary()
  },
  methods: {
    init(){
      this.total=0
      this.data =Object.assign({}, this.equipmentData.planAssetContractDto, this.equipmentData.billConfigCloudDto) 
      this.businessAttachmentMapListCloudDto = this.equipmentData.businessAttachmentMapListCloudDto || []
      this.fileList = this.equipmentData.businessAttachmentMapListCloudDto || []
      this.paymentItemListCloudDto = this.equipmentData.paymentItemListCloudDto || []

      let total = 0

      this.paymentItemListCloudDto.forEach(ele=>{
        if (!isNaN(Number(ele.paymentAmount))) {
          total = Number(total) + Number(ele.paymentAmount)
        }
      })

      this.total = Number(total).toFixed(2)
      if(this.businessAttachmentMapListCloudDto&&this.businessAttachmentMapListCloudDto.length>0){
        this.showFile = true
      }
    },
    spacePartitionChange(primaryKey){
      this.data.floor = null
      let arr = []
      if(primaryKey){
        if(this.getDictionaryDetail.businessFloor){
          this.getDictionaryDetail.businessFloor.forEach(element => {
            if(element.partitionKey == primaryKey)arr.push(element)
          });
        }
      }
      this.floor = arr
    },
     async getDictionary(systemKey = null) {
      const res = await Api.dictionary({
        projectKey: this.$route.query.projectKey,
        systemKey,
      });
      this.getDictionaryDetail = res
      if (res && res.success) {
        if (!systemKey) {
          //楼层
          this.floor = res.businessFloor;
          //设施
          if (res.baseStation && res.baseStation.success) {
            this.facility = res.baseStation.rows;
          }
          //分区
          if (res.spacePartition && res.spacePartition.success) {
            this.spacePartition = res.spacePartition.rows;
          }
          //子系统
          if (res.systemInfo && res.systemInfo.success) {
            this.system = res.systemInfo.rows;
          }
        } else {
          //设备deviceInfo
          if (res.deviceInfo && res.deviceInfo.success) {
            this.device = res.deviceInfo.rows;
          }
        }
      }
    },
   //保存
    async save() {
      this.$refs.form.validate(async isOK => {
        if (isOK) {
          let params ={
            assetCode:this.assetCode,
            planKey:this.$route.query.planKey,
            billConfigCloudDto:this.data,
            paymentItemListCloudDto:this.paymentItemListCloudDto,
            businessAttachmentMapListCloudDto:this.businessAttachmentMapListCloudDto
          }
          const res = await Api.configverify(params);
          if (res && res.success) {
            this.configverify = res;
            if (res.vilidateResult) {
              this.showFile = false
              this.search(params);
            } else {
              this.errorMessage = res
              this.showFile = true
              this.$message.warning('校验失败');
            }
          }
        }
      });
    },
    // 确定
    async search(params) {
      this.$refs.form.validate(async isOK => {
        if (isOK) {
          if (this.showFile) {
            if (this.businessAttachmentMapListCloudDto&&businessAttachmentMapListCloudDto.length>0 ) {
              this.$message.warning('文件和说明不能为空！');
              return;
            }
          }
          const res = await Api.create(params);
          if (res && res.success) {
            this.$emit('close-dialog2');
            this.closeDialog()
            this.$message.success(res.message);
            this.$parent.getData();
          }
        }
      });
    },
    focus(index){
      this.num1 = this.paymentItemListCloudDto[index].paymentAmount || 0
    },
    changePrice(index){
      let num2 = this.paymentItemListCloudDto[index].paymentAmount  || 0

      let total = this.total
      total = Number(total) - Number(this.num1) + Number(num2)

      this.total = Number(total).toFixed(2)
    },
    addPlan(){
      if(!this.isEdit){
        return
      }
      this.paymentItemListCloudDto.push({
        paymentDate:'',
        paymentAmount:''
      })
    },
    remove(index){
      if(!this.isEdit){
        return
      }
      let num = this.paymentItemListCloudDto[index].paymentAmount || 0
      this.total = Number(this.total)-Number(num)
      this.paymentItemListCloudDto.splice(index, 1);
    },
    beforeupload(file, a) {
      uploadPhoto(file).then(res => {
        this.fileList.push(file)
        this.businessAttachmentMapListCloudDto = [{ fileUrl: res.data.rows[0].url, fileTitle: res.data.rows[0].originalName, fileId: res.data.rows[0].key,uid:file.uid }];
        this.$message.success('上传成功');
      });
    },
    handleRemove(file){
      this.businessAttachmentMapListCloudDto.forEach(((ele,index)=>{
        if(ele.uid == file.uid){
          this.businessAttachmentMapListCloudDto.splice(index, 1)
        }
      }))
    },
    DownFile(file) {
      window.open(file.fileUrl);
    },
    closeDialog(){
      this.fileList = []
      this.businessAttachmentMapListCloudDto=[]
      this.paymentItemListCloudDto = []
    }
  },
};
</script>

<style lang="scss" scoped>

.el-row .el-col {
  height: 50px;
}
.addSpan {
  color: #33b5ff;
  cursor: pointer;
}
.textSpan {
  color: #bf4747;
}
.text-del {
  cursor: pointer;
  color: #33b5ff;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
